//
//  TaxAuthVC.m
//  NtoccDriverNew
//
//  Created by mac on 2021/1/11.
//  Copyright © 2021 GCY. All rights reserved.
//

#import "TaxAuthVC.h"
#import "TZImagePickerController.h"

//人脸识别
#ifdef isOpenBaiDuFaceSDK

#import "BDFaceLivenessViewController.h"
#import "BDFaceDetectionViewController.h"
#import "BDFaceLivingConfigModel.h"
#import "IDLFaceSDK/IDLFaceSDK.h"
#import "FaceParameterConfig.h"

#endif

#define TaxWindowView [UIApplication sharedApplication].delegate.window

#define K_MAIN_VIEW_SCROLL_HEIGHT SX(30)
#define K_MAIN_VIEW_SCROLL_TEXT_TAG 300
#define K_MAIN_VIEW_TEME_INTERVAL 0.35                //计时器间隔时间(单位秒)
#define K_MAIN_VIEW_SCROLLER_SPACE 20.0f              //每次移动的距离
#define K_MAIN_VIEW_SCROLLER_LABLE_WIDTH     18.0f    //单个字符宽度(与你设置的字体大小一致)
#define K_MAIN_VIEW_SCROLLER_LABLE_MARGIN    20.0f    //前后间隔距离
#define K_MAIN_VIEW_SCROLLER_SLEEP_INTERVAL  1        //停留时间

@interface TaxAuthVC ()<TZImagePickerControllerDelegate, UIImagePickerControllerDelegate>
{
    NSTimer        *timer;
    UIScrollView   *scrollViewText;
    NSArray        *_driverVerifyList;
    NSMutableArray *_reslutTiArr;
    UIImagePickerController *_ipc;//图片选择器
    
}

@property (nonatomic ,strong) NSArray *arrData;

@end

@implementation TaxAuthVC

- (void)dealloc {
    
    [KNotificationCenter removeObserver:self name:@"faceIdentifySuccess" object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    //    [timer invalidate];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    _ipc = [[UIImagePickerController alloc] init];
    _ipc.delegate = self;
    _ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
    _ipc.showsCameraControls = YES;
    
    [KNotificationCenter addObserver:self selector:@selector(faceIdentifyCompleted:) name:@"faceIdentifySuccess" object:nil];
    
    self.navigationItem.title = @"税务认证";
    
    self.view.backgroundColor = [UIColor cy_colorWithHexString:@"#F1F1F1"];
    
    [self layoutMainViews];
    
}

- (void)layoutMainViews {
    
    UIView *topBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenW, SX(30))];
    topBgView.backgroundColor = [UIColor colorWithHexString:@"#DEE6F2"];
    topBgView.tag = 10;
    [self.view addSubview:topBgView];
    
    UIImageView *lImg = [[UIImageView alloc] initWithFrame:CGRectMake(SX(15), 0, SX(14.5f), SY(13.5f))];
    lImg.image = image(@"gcy_my_taxauthmsg");
    lImg.centerY = topBgView.centerY;
    [topBgView addSubview:lImg];
    
    NSDictionary *userInfo = [UserDefaultUtil valueForKey:Login_Branch];
    //    NSString *msgTexttr = @"这里是引导语最多显示25字符超出可滚动显示";
    NSString *msgTexttr = [userInfo valueForKey:@"taxVerifyNote"];
    
    if (msgTexttr.length <= 25) {
        UILabel *tLabel = [[UILabel alloc] init];
        tLabel.textColor = Theme_ColorValue;
        tLabel.text = msgTexttr;
        tLabel.font = font(13);
        [topBgView addSubview:tLabel];
        
        [tLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(SX(35));
            make.right.height.equalTo(topBgView);
        }];
        
    } else {
        
        [self initScrolTextView:msgTexttr];
    }
    
    _reslutTiArr = [NSMutableArray array];
    NSMutableArray *reslutImgArr = [NSMutableArray array];
    
    _driverVerifyList = [[UserDefaultUtil valueForKey:Login_Branch] objectForKey:@"driverVerifyList"];
    if ([DCSpeedy isBlankArr:_driverVerifyList] == NO) {
        
        [_driverVerifyList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([[obj objectForKey:@"verifyType"] isEqual:@"1"]) {
                [_reslutTiArr addObject:[obj objectForKey:@"verifyName"]];
                [reslutImgArr addObject:@"gcy_my_taxauthtj"];
            }
            if ([[obj objectForKey:@"verifyType"] isEqual:@"2"]) {
                [_reslutTiArr addObject:[obj objectForKey:@"verifyName"]];
                [reslutImgArr addObject:@"gcy_my_taxauthjc"];
            }
        }];
        
        for (int i=0; i<_reslutTiArr.count; i++) {
            
            UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, topBgView.bottom + SY(10) + SY(55)*i, ScreenW, SY(55))];
            bgView.backgroundColor = [UIColor colorWithHexString:@"#ffffff"];
            [self.view addSubview:bgView];
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.backgroundColor = [UIColor whiteColor];
            button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            [button setImage:image(reslutImgArr[i]) forState:UIControlStateNormal];
            button.titleLabel.font = font(15);
            [button addTarget:self action:@selector(buttonTypeClick:) forControlEvents:UIControlEventTouchUpInside];
            [button setTitleColor:Dark_TextColor forState:UIControlStateNormal];
            [button setTitle:_reslutTiArr[i] forState:UIControlStateNormal];
            button.frame = CGRectMake(SX(20), 0, bgView.width-SX(40), bgView.height);
            [bgView addSubview:button];
            
            [button layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleLeft imageTitleSpace:SX(5)];
            
            if (i>0) {
                UIView *line = [[UIView alloc] initWithFrame:CGRectMake(SX(15), 0, ScreenW-SX(30), SY(1))];
                line.backgroundColor = [UIColor cy_colorWithHexString:@"#E4E9ED"];
                [bgView addSubview:line];
            }
            
            CGSize size = [DCSpeedy dc_calculateTextSizeWithText:_reslutTiArr[i] WithTextFont:15 WithMaxW:1000];
            
            UIImageView *rIcon = [[UIImageView alloc] initWithFrame:CGRectMake(size.width + SX(50), SY(15.5f), SX(24), SY(24))];
            rIcon.contentMode = UIViewContentModeScaleAspectFit;
            rIcon.image = image(@"gcy_icon_my_yirenzheng");
            [bgView addSubview:rIcon];
            
            ///
            NSInteger index = [_reslutTiArr indexOfObject:button.titleLabel.text];
            if ([[[_driverVerifyList objectAtIndex:index] objectForKey:@"verifyStatus"] intValue] == 1) {
                rIcon.image = image(@"gcy_icon_my_yirenzheng");
            } else {
                rIcon.image = image(@"gcy_img_acc_zhuxiao");
            }
        }
        
    } else {
        
        [XSInfoView showInfo:@"暂无数据" onView:self.view];

    }
    
}

- (void)buttonTypeClick:(UIButton *)button {
    
    NSInteger index = [_reslutTiArr indexOfObject:button.titleLabel.text];
    if ([[[_driverVerifyList objectAtIndex:index] objectForKey:@"verifyStatus"] intValue] == 1) {
        [XSInfoView showInfo:@"核验已通过" onView:self.view];
        return;
    }
    
    if ([button.titleLabel.text containsString:@"活体"]) {
        if ([[[_driverVerifyList objectAtIndex:0] objectForKey:@"verifyStatus"] intValue] == 1) {
            [XSInfoView showInfo:@"已核验通过" onView:self.view];
            return;
        }
        
        //天津税务，走百度人脸
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], PERSONALCENTER_INDEX) withParameter:@{@"token":[UserDefaultUtil valueForKey:USER_TOKEN]} withVC:self netName:@"个人中心初始化" success:^(id response, NSString *msg) {
            
            if ([response[@"isRealPeople"] intValue] == 1) {
                //已进行了人脸核验
                [XSInfoView showInfo:msg onView:self.view];
            } else {
                //未进行人脸核验
                if ([response[@"authStatus"] intValue] == 3) {
                    //平台认证已通过，去认证人脸
#ifdef isOpenBaiDuFaceSDK
                    if (![[FaceSDKManager sharedInstance] canWork]) {
                        NSString* licensePath = [NSString stringWithFormat:@"%@.%@", FACE_LICENSE_NAME, FACE_LICENSE_SUFFIX ];
                        [[FaceSDKManager sharedInstance] setLicenseID:FACE_LICENSE_ID andLocalLicenceFile:licensePath andRemoteAuthorize:YES];
                    }
                    [self faceLiveness];
#endif
                } else {
                    [XSInfoView showInfo:@"您的信息未认证,请先认证信息" onView:self.view];
                }
            }
            
        } failure:^(NSInteger code, NSString *msg) {
            
        }];
        
    } else if ([button.titleLabel.text containsString:@"照片"]) {
        if ([[[_driverVerifyList objectAtIndex:1] objectForKey:@"verifyStatus"] intValue] == 1) {
            [XSInfoView showInfo:@"已核验通过" onView:self.view];
            return;
        }
        
        //金昌税务，走拍照识别
        //        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], DRIVER_VERIFYIDENTITYONOFF) withParameter:@{@"branchCode": [UserDefaultUtil valueForKey:BranchCode], @"token":[UserDefaultUtil valueForKey:USER_TOKEN],} withVC:self netName:@"是否开启身份验证" success:^(id response, NSString *msg) {
        //            if ([response[@"toVerifyIdentity"] integerValue] == 2) {
        //
        //
        //
        //            } else if ([response[@"toVerifyIdentity"] integerValue] == 0) {
        //                [XSInfoView showInfo:@"未开启该功能开关，请联系管理员" onView:self.view];
        //            }
        //
        //        } failure:^(NSInteger code, NSString *msg) {
        //
        //        }];
        
        //        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 columnNumber:3 delegate:self pushPhotoPickerVc:YES];
        //        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        //
        //            [HTTPManager postUploadFiles:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tps-api",[ReAddressDynamic shared].baseUrl], FILE_UPLOAD) file:@[[photos firstObject]] fileName:@"file" withVC:self netName:@"文件上传" success:^(id response, NSString *msg) {
        //
        //                NSDictionary *parmas = @{
        //                    @"peopleImg": response[@"data"],
        //                    @"branchCode": [UserDefaultUtil valueForKey:BranchCode],
        //                    @"token":[UserDefaultUtil valueForKey:USER_TOKEN],
        //                };
        //                [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/driver/verifyIdentityImg", BasicDomainURL) withParameter:parmas withVC:self netName:@"拍照身份验证" success:^(id response, NSString *msg) {
        //
        //                    [XSInfoView showInfo:response[@"msg"] onView:self.view];
        //
        //                    if ([response[@"pass·"] integerValue] == 1) {
        //                        [self.navigationController popToRootViewControllerAnimated:YES];
        //                    }
        //
        //                } failure:^(NSInteger code, NSString *msg) {
        //
        //                }];
        //
        //            } failure:^(NSInteger code, NSString *msg) {
        //
        //            }];
        //
        //        }];
        //        imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
        //        [self presentViewController:imagePickerVc animated:YES completion:nil];
        
        [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-basic-api",[ReAddressDynamic shared].baseUrl], PERSONALCENTER_INDEX) withParameter:@{@"token":[UserDefaultUtil valueForKey:USER_TOKEN]} withVC:self netName:@"个人中心初始化" success:^(id response, NSString *msg) {
            
            if ([response[@"isRealPeople"] intValue] == 1) {
                //已进行了人脸核验
                [XSInfoView showInfo:msg onView:self.view];
            } else {
                //未进行人脸核验
                if ([response[@"authStatus"] intValue] == 3) {
                    //平台认证已通过
                    [self presentViewController:_ipc animated:YES completion:nil];
                    
                } else {
                    [XSInfoView showInfo:@"您的信息未认证,请先认证信息" onView:self.view];
                }
            }
            
        } failure:^(NSInteger code, NSString *msg) {
            
        }];
        
    }
}

#pragma mark - TZImagePickerControllerDelegate
- (BOOL)isAssetCanSelect:(PHAsset *)asset {
    return NO;
}

#ifdef isOpenBaiDuFaceSDK
//人脸认证相关
- (void)faceLiveness {
    BDFaceLivenessViewController* lvc = [[BDFaceLivenessViewController alloc] init];
    BDFaceLivingConfigModel* model = [BDFaceLivingConfigModel sharedInstance];
    [lvc livenesswithList:model.liveActionArray order:model.isByOrder numberOfLiveness:model.numOfLiveness];
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:lvc];
    navi.navigationBarHidden = true;
    navi.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:navi animated:YES completion:nil];
}

- (void)faceIdentifyCompleted:(NSNotification *)notifi {
    
    NSDictionary *parmas = @{
        @"peopleImg": notifi.object,
    };
    [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/driver/driverRealPeopleCertification", BasicDomainURL) withParameter:parmas withVC:self netName:@"百度人证核验结果通知" success:^(id response, NSString *msg) {
        
        [SVProgressHUD showSuccessWithStatus:@"核验成功！"];
        [SVProgressHUD dismissWithDelay:1.0f completion:^{
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
        
    } failure:^(NSInteger code, NSString *msg) {
        
    }];
}

#endif


#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    //判断媒体资源类型，（图片或者是视频）
    NSString *imageType = [info objectForKey:UIImagePickerControllerMediaType];
    UIImage *gerenimage = [[UIImage alloc] init];
    //如果是图片资源
    if ([imageType isEqualToString:(NSString *)kUTTypeImage]) {
        //取到从系统图片库选择的图片或者照相机拍摄的图片
        if (_ipc.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
            gerenimage = [info objectForKey:UIImagePickerControllerOriginalImage];
        }else if(_ipc.sourceType == UIImagePickerControllerSourceTypeCamera){
            gerenimage = [info objectForKey:UIImagePickerControllerOriginalImage];
        }
        UIImageOrientation imageOrientation = gerenimage.imageOrientation;
        if(imageOrientation!=UIImageOrientationUp)
        {
            // 原始图片可以根据照相时的角度来显示，但UIImage无法判定，于是出现获取的图片会向左转９０度的现象。
            // 以下为调整图片角度的部分
            UIGraphicsBeginImageContext(gerenimage.size);
            [gerenimage drawInRect:CGRectMake(0, 0, gerenimage.size.width, gerenimage.size.height)];
            gerenimage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            // 调整图片角度完毕
        }
        
    }
    
    NSMutableArray *muArr = [[NSMutableArray alloc] init];
    [muArr addObject:gerenimage];
    
    //发送头像请求
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [HTTPManager postUploadFiles:CJStringWithFormat(@"%@%@", [NSString stringWithFormat:@"%@/ntocc-tps-api",[ReAddressDynamic shared].baseUrl], FILE_UPLOAD) file:muArr fileName:@"file" withVC:self netName:@"文件上传" success:^(id response, NSString *msg) {
            
            NSDictionary *parmas = @{
                @"peopleImg": response[@"data"],
                @"branchCode": [UserDefaultUtil valueForKey:BranchCode],
                @"partyCode":[UserDefaultUtil valueForKey:DriverPartyCode],
            };
            [HTTPManager getNetworkRequest:CJStringWithFormat(@"%@/ntocc-basic-api/driver/faceVerify", BasicDomainURL) withParameter:parmas withVC:self netName:@"拍照验证" success:^(id response, NSString *msg) {
                
                [XSInfoView showInfo:@"核验通过" onView:TaxWindowView];
                
                [self.navigationController popToRootViewControllerAnimated:YES];
                
            } failure:^(NSInteger code, NSString *msg) {
                
            }];
            
        } failure:^(NSInteger code, NSString *msg) {
            
        }];
        
    });
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    
    //更改picker的导航条颜色 及item的tintcolor
    if ([_ipc.navigationBar respondsToSelector:@selector(setBarTintColor:)]) {
        _ipc.navigationBar.tintColor = [UIColor cy_colorWithHexString:@"484848"];
        _ipc.navigationBar.translucent = NO;
        _ipc.navigationBar.barTintColor = [UIColor whiteColor];
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
        
        //设置导航标题的属性
        [_ipc.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor cy_colorWithHexString:@"484848"], NSFontAttributeName: [UIFont systemFontOfSize:18]}];
        //        _ipc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;//弹出模式
        _ipc.allowsEditing = YES;
    }
    
}

#pragma mark - 滚动文字创建
-(void) initScrolTextView:(NSString *)title{
    
    if (!self.arrData) {
        self.arrData = @[
            
            @{
                @"newsId"    :@"201507070656471857",
                @"newsImg"   :@"http://bg.fx678.com/HTMgr/upload/UpFiles/20150707/2015070706533134.jpg",
                @"newsTitle" :title
            }
        ];
    }
    
    //文字滚动
    [self initScrollText];
    
    //开启滚动
    [self startScroll];
    
}


//文字滚动初始化
-(void) initScrollText{
    UIView *topBgView = [self.view viewWithTag:10];
    //获取滚动条
    scrollViewText = (UIScrollView *)[self.view viewWithTag:K_MAIN_VIEW_SCROLL_TEXT_TAG];
    if(!scrollViewText){
        scrollViewText = [[UIScrollView alloc] initWithFrame:CGRectMake(SX(35), 0, self.view.frame.size.width, K_MAIN_VIEW_SCROLL_HEIGHT)];
        scrollViewText.showsHorizontalScrollIndicator = NO;   //隐藏水平滚动条
        scrollViewText.showsVerticalScrollIndicator = NO;     //隐藏垂直滚动条
        scrollViewText.scrollEnabled = NO;                    //禁用手动滑动
        
        //横竖屏自适应
        scrollViewText.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        scrollViewText.tag = K_MAIN_VIEW_SCROLL_TEXT_TAG;
        
        //给滚动视图添加事件
        //        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scrollerViewClick:)];
        //        [scrollViewText addGestureRecognizer:tapGesture];
        
        //添加到当前视图
        [topBgView addSubview:scrollViewText];
        
    }else{
        //清除子控件
        for (UIView *view in [scrollViewText subviews]) {
            [view removeFromSuperview];
        }
    }
    
    if (self.arrData) {
        
        CGFloat offsetX = 0 ,i = 0, h = 30;
        
        //设置滚动文字
        UIButton *btnText = nil;
        NSString *strTitle = [[NSString alloc] init];
        
        for (NSDictionary *dicTemp in self.arrData) {
            
            strTitle = dicTemp[@"newsTitle"];
            
            btnText = [UIButton buttonWithType:UIButtonTypeCustom];
            [btnText setFrame:CGRectMake(0,
                                         (K_MAIN_VIEW_SCROLL_HEIGHT - h) / 2,
                                         strTitle.length * K_MAIN_VIEW_SCROLLER_LABLE_WIDTH,
                                         h)];
            
            btnText.titleLabel.font = font(13);
            [btnText setTitleColor:Theme_ColorValue forState:UIControlStateNormal];
            [btnText setTitle:strTitle forState:UIControlStateNormal];
            
            //横竖屏自适应
            btnText.autoresizingMask = UIViewAutoresizingFlexibleWidth;
            offsetX += btnText.frame.origin.x;
            
            //设置为 NO,否则无法响应点击事件
            btnText.userInteractionEnabled = NO;
            
            //添加到滚动视图
            [scrollViewText addSubview:btnText];
            
            i++;
        }
        
        //设置滚动区域大小
        [scrollViewText setContentSize:CGSizeMake(offsetX, 0)];
    }
}


#pragma mark - 滚动处理
//开始滚动
-(void) startScroll{
    
    if (!timer)
        timer = [NSTimer scheduledTimerWithTimeInterval:K_MAIN_VIEW_TEME_INTERVAL target:self selector:@selector(setScrollText) userInfo:nil repeats:YES];
    
    [timer fire];
    
}


//滚动处理
-(void) setScrollText{
    
    [UIView animateWithDuration:K_MAIN_VIEW_TEME_INTERVAL * 2 animations:^{
        CGRect rect;
        CGFloat offsetX = 0.0,width = 0.0;
        
        for (UIButton *btnText in scrollViewText.subviews) {
            
            rect = btnText.frame;
            offsetX = rect.origin.x - K_MAIN_VIEW_SCROLLER_SPACE;
            width = [btnText.titleLabel.text length] * K_MAIN_VIEW_SCROLLER_LABLE_WIDTH;
            
            btnText.frame = CGRectMake(offsetX, rect.origin.y, rect.size.width, rect.size.height);
            
            //            NSLog(@"offsetX:%f",offsetX);
        }
        
        if (offsetX < -width){
            [UIView setAnimationsEnabled:NO];
            [self initScrollText];
        }else
            [UIView setAnimationsEnabled:YES];
    }];
    
}


#pragma mark - 动态获取左边位置
-(float) getTitleLeft:(CGFloat) i {
    float left = i * K_MAIN_VIEW_SCROLLER_LABLE_MARGIN;
    //    float left = SX(35);
    
    if (i > 0) {
        for (int j = 0; j < i; j ++) {
            left += [[self.arrData objectAtIndex:j][@"newsTitle"] length] * K_MAIN_VIEW_SCROLLER_LABLE_WIDTH;
        }
    }
    
    return left;
}


#pragma mark - 新闻点击事件
-(void)btnNewsClick:(UIButton *) sender{
    
    
}

-(void)scrollerViewClick:(UITapGestureRecognizer*)gesture{
    
    CGPoint touchPoint = [gesture locationInView:scrollViewText];
    
    for (UIButton *btn in scrollViewText.subviews) {
        
        if ([btn.layer.presentationLayer hitTest:touchPoint]) {
            [self btnNewsClick:btn];
            break;
        }
        
    }
    
}
@end
